package com.mvc.business.service;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mvc.business.model.OrderCharge;
import com.mvc.framework.model.Auditable;
import com.mvc.framework.service.BaseService;

/** 
 * 
 * @author  snowpbx
 * @version V1.0  Create Time: 2012-10-15
 */
@Service
public class OrderChargeManager extends BaseService<OrderCharge, Integer> {

	@Autowired
	private OrderManager orderManager;

	public List<OrderCharge> getOrderChargesByOrderId(int orderId) {
		OrderCharge orderItem = new OrderCharge();
		orderItem.setOrderId(orderId);
		orderItem.setRecStatus(Auditable.REC_STATUS_VALID);
		return getHibernateTemplate().findByExample(orderItem);
	}

	public void deleteByOrderId(int orderId) {
		deleteByWhere("orderId=" + orderId);
	}

	public void saveOrderItem(OrderCharge orderItem, String operation) throws Exception {
		if (operation.equals("del")) {
			super.delete(orderItem.getId());
		} else if (operation.equals("add")) {
			orderItem.setId(null);
			super.save(orderItem);
		} else if (operation.equals("edit")) {
			super.save(orderItem);
		}
		orderManager.updateTotal(orderItem.getOrderId());
	}
	
	public void updateOrderId(Integer oldOrderId, Integer newOrderId) {
		Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
		Query query = session.createQuery("update " + OrderCharge.class.getName() + " set orderId = " + newOrderId
				+ " where orderId = " + oldOrderId);
		query.executeUpdate();
	}
}

